package com.atguigu.msmservice.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.msmservice.service.SendSmsService;
import org.springframework.stereotype.Service;

@Service
public class SendSmsServiceImpl implements SendSmsService {

    /**
     * 短信验证实现类
     *
     * @param phoneNumber
     * @param templateCode
     * @param code
     * @return
     */
    @Override
    public boolean send(String phoneNumber, String templateCode, String code) {
//        System.out.println("1111111111111111" + code);
        //连接阿里云 短信验证
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FznP3gQfNNGJqK4sYmV", "CU954Elezebtu8Ywj04sPz0EmjgJQS");
        IAcsClient client = new DefaultAcsClient(profile);

        //构建请求
        CommonRequest request = new CommonRequest();

        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");//发送短信的样子，事件的名称

        //自定义参数（手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "乡村旅游网");
        request.putQueryParameter("TemplateCode", templateCode);
        //构建一个短信的验证码
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("code",4548);
        // 生成随机验证码
        //  String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000); // 生成短信验证码
        //  System.out.println("发送的验证码"+verifyCode);
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");


        try {
            CommonResponse response = client.getCommonResponse(request);
            //System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
